<?php
/**
 * Created by PhpStorm.
 * User: Administratorjing
 * Date: 2018/3/25/025
 * Time: 14:03
 */

namespace app\lib\exception;


use think\Exception;
use think\exception\Handle;
use think\Log;
use think\Request;

class ExceptionHandler extends Handle
{
    private $code;
    private $msg;
    private $errorCode;
    //need to return the client's current url path
    public function render(\Exception $e)
    {
        if($e instanceof BaseException)
        {
            //if it is a custom exception
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;
        }else{
            //$switch = true;
            if(config('app_debug'))
            {
                //return the default page
                return parent::render($e);
            }
            $this->code = 500;
            $this->msg = '服务器很生气，什么都不想做';
            $this->errorCode = 999;
            $this->recordErrorLog($e);
        }
        //take the current url
        $request = Request::instance();
        //define the return of result
        $result = [
            'msg' => $this->msg,
            'error_code' => $this->errorCode,
            'request_url' => $request = $request->url()
        ];
        //return the json format
        return json($result,$this->code);
    }

    /**
     * write the error to log
     * @param Exception $e
     */
    private function recordErrorLog(\Exception $e)
    {
        //initialization log
        Log::init([
            'type' => 'File',
            'path' => LOG_PATH,
            //just record the error and the level more than error
            'level' => ['error']
        ]);
        Log::record($e->getMessage(),'error');
    }
}